package com.example.servlettemplate.servlet;


import com.example.servlettemplate.dao.UserDAO;
import com.example.servlettemplate.pojo.User;
import com.example.servlettemplate.util.RequestUtil;
import com.example.servlettemplate.util.SystemConstants;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebServlet("/password")
public class PasswordServlet extends HttpServlet {

    private UserDAO userDAO = new UserDAO();

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String password = RequestUtil.getString(req, "password");
        if (password == null) {
            error("原始密码不能为空", req, resp);
            return;
        }
        String newPassword = RequestUtil.getString(req, "newpwd");
        if (newPassword == null) {
            error("新密码不能为空", req, resp);
            return;
        }
        String repeatPassword = RequestUtil.getString(req, "repeatPassword");
        if (repeatPassword == null) {
            error("确认密码不能为空", req, resp);
            return;
        }
        if (!newPassword.equals(repeatPassword)) {
            error("两次输入的新密码不一致", req, resp);
            return;
        }
        HttpSession session = req.getSession();
        User sessionUser = (User) session.getAttribute(SystemConstants.SESSION_USER);
        User user = userDAO.getUserById(sessionUser.getId());
        if(!user.getPassword().equals(password)){
            error("原始密码错误", req, resp);
            return;
        }
        int result = userDAO.updatePassword(user.getId(), newPassword);
        if(result == 1){
            //修改成功后返回登录页
            req.getRequestDispatcher(SystemConstants.PAGE_PATH + "login.jsp").forward(req, resp);
        }else {
            error("修改失败，请稍后再试", req, resp);
        }


    }

    public void error(String message, HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setAttribute("message", message);//动态错误信息message
        req.getRequestDispatcher(SystemConstants.PAGE_PATH + "password.jsp").forward(req, resp);//请求转发跳转页面
    }

}